package sw.controller;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sw.dao.UserGroupDao;
import sw.entity.Asset;
import sw.entity.Project;
import sw.model.MAsset;
import sw.model.MMenu;
import sw.model.MProject;
import sw.model.MResult;
import sw.model.MRiskLevel;
import sw.model.MUserGroup;
import sw.model.MUserGroupProject;

@Controller
@RequestMapping("/pro")
public class ProjectController extends BaseController {

	public ProjectController(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}

	/**
	 * 显示项目列表
	 * @param model
	 * @return
	 */
	@GetMapping("/projectList")
	public String showProjectPage(HttpServletRequest request,Model model) {// 
		HttpSession session = request.getSession();
		// if (session.getAttribute(SESSION_KEY) != null)
		List<Project> projects = projectService.findCreateProjectByUserId(1);//session.getAttribute(SESSION_KEY)
		Collection<MUserGroupProject> joinProjects = projectService
				.findJoinProjectByUserId(1);
		model.addAttribute("projects", projects);
		model.addAttribute("joinProjects", joinProjects);
		return "/RA/index";
	}
	
	/**
	 * 跳转到添加项目页面
	 * @param model
	 * @return
	 */
	@GetMapping("/projectForm")
	public String showProjectFormView(Model model) {//
		model.addAttribute("project", new Project());
		return "/RA/addProject";
	}
	
	/**
	 * 保存项目基本信息
	 * @param mProject
	 * @param file
	 * @return
	 */
	@PostMapping("/addProjectInfo")
	public String project(@ModelAttribute("project") Project project, MultipartFile file,Model model){
		String gplotName = uploadGplot(file);
		if(!"-1".equals(gplotName)){//上传成功
			project.setGplot(gplotName);
		}
		project = projectService.save(project);
		model.addAttribute("project",project);
		return "/RA/addCollege";
	}
	/**
	 * 添加人员
	 * @param userGroup
	 * @return
	 */
	@GetMapping("/addCollege")
	public void addCollege(MUserGroup userGroup){
		groupAuthManger.addUserFromGroup(userGroup);
	}
	
	//跳转页面
	@GetMapping("/skipAddLevel")
	public String skip(Integer projectId,Model model){
		model.addAttribute("projectId", projectId);
		return "RA/addLevel";
	}
	
	/**
	 * 添加等级
	 * @return
	 */
	@GetMapping("/addLevel")
	@ResponseBody
	public void addLevel(MRiskLevel level){
		riskCalService.saveRiskLevel(level);
	}
	
	
	
	/**
	 * 保存项目及其相关信息
	 * @param mProject
	 * @param model
	 * @return
	 */
	@PostMapping("/projectAdd")
	public String projectAdd(@ModelAttribute("project") MProject mProject,
			Model model) {
		projectService.save(mProject);
		return "/RA/index";
	}
	

	


//	@GetMapping("/projectForm/{id}")
//	public String showProjectForm(@PathVariable int id, Model model) {
//		Project project = projectService.findById(id);
//		model.addAttribute("project", project);
//		model.addAttribute("operation", "update");
//		return "/pages/project/ProjectForm";
//	}

//	@PostMapping("/updateProject")
//	public String updateProject(@ModelAttribute("project") Project project) {
//		// projectService.save(project);
//		return "redirect:/pro/projectList";
//	}

	
	/**
	 * 删除项目信息
	 * @param id
	 * @return
	 */
	@GetMapping("/delProject/{id}")
	public String delPeoject(@PathVariable int id) {
		projectService.delete(id);
		return "redirect:/pro/projectList";
	}

	/**
	 * 显示项目详情页
	 * @param projectId
	 * @param groupIds
	 * @param model
	 * @return
	 */
	@GetMapping("/projectMain/{projectId}/{groupIds}")
	public String showProjectMain(@PathVariable int projectId,
			@PathVariable String groupIds, Model model) {
		Integer[] groupArr = null;
		if (!groupIds.equals("-1")) {// 有权限组，就是自己参与的项目
			String[] strGroupArr = groupIds.split(",");
			groupArr = new Integer[strGroupArr.length];
			for (int i = 0; i < strGroupArr.length; i++) {
				groupArr[i] = Integer.valueOf(strGroupArr[i]);
			}
		} else {// 没有权限组就是自己创建的项目
			groupArr = leftMenuServiceImpl.findFirstMenu();
		}
		
		String groupString = String.valueOf(groupArr[0]);
		for(int i =1;i<groupArr.length;i++){
			groupString += ","+String.valueOf(groupArr[i]);
		}
		model.addAttribute("projectId", projectId);
		model.addAttribute("groupArr", groupString);
		model.addAttribute("menuList",getMuenList(groupArr) );
		model.addAttribute("project",projectService.getProject(1, projectId));//项目信息
		return "/RA/project";
	}

	/**
	 * 
	 * @param projectId
	 * @param groupArr
	 * @param currMenuId
	 * @param model
	 * @return
	 */
	@GetMapping("/pageLink/{projectId}/{groupIds}/{currMenuId}")
	public String showProjectMenu(@PathVariable int projectId,
			@PathVariable String groupIds, @PathVariable Integer currMenuId,
			Model model) {
		String href = null;
		String[] strGroupArr = groupIds.split(",");
		Integer[] groupArr = new Integer[strGroupArr.length];
		for (int i = 0; i < strGroupArr.length; i++) {
			groupArr[i] = Integer.valueOf(strGroupArr[i]);
		}
		
		 List<MMenu> menuList = getMuenList(groupArr);
		for (MMenu mu : menuList) {
			if (currMenuId == mu.getId()) {
				href = mu.getHref();
				break;
			}
		}

		model.addAttribute("projectId", projectId);
		model.addAttribute("groupArr", groupIds);
		model.addAttribute("menuList", menuList);

		switch(currMenuId){
			case 1://项目详情页面
				model.addAttribute("project",projectService.getProject(1, projectId));//项目信息
				break;
			case 2://资产识别页面
				model.addAttribute("assetMap",assetService.findByprojectIdGroupByType(projectId));//资产信息
				break;
			case 3://重要资产赋值页面
				Map<String, List<Asset>> impAssetGroups = assetService.findImpProGroupByType(projectId);
				model.addAttribute("impAssetGroups", impAssetGroups); 
				break;
			case 4://威胁识别赋值
				Map<String, List<MAsset>> threatGroups = threatService.showAllThreads(projectId);
				model.addAttribute("threatGroups", threatGroups); 
				break;
			case 5://脆弱性识别与赋值
				Map<String, List<MAsset>> weakGroups = weaknessService.showAllWeekness(projectId);
				model.addAttribute("weakGroups", weakGroups); 
				break;
			case 6:
				 Map<String, List<MResult>> resultMap = riskCalService.showResult(projectId);
				 model.addAttribute("resultMap", resultMap); 
				  break;
		}
		return href;
	}
	
	@GetMapping("/pageLinkjson/{projectId}/{groupIds}/{currMenuId}")
	@ResponseBody
	public String showProjectMenuJSON(@PathVariable int projectId,
			@PathVariable String groupIds, @PathVariable Integer currMenuId,
			Model model) {
		String href = null;
		String[] strGroupArr = groupIds.split(",");
		Integer[] groupArr = new Integer[strGroupArr.length];
		for (int i = 0; i < strGroupArr.length; i++) {
			groupArr[i] = Integer.valueOf(strGroupArr[i]);
		}
		
		 List<MMenu> menuList = getMuenList(groupArr);
		for (MMenu mu : menuList) {
			if (currMenuId == mu.getId()) {
				href = mu.getHref();
				break;
			}
		}
		model.addAttribute("projectId", projectId);
		model.addAttribute("groupArr", groupIds);
		model.addAttribute("menuList", menuList);
		switch(currMenuId){
			case 1://项目详情页面
				model.addAttribute("project",projectService.getProject(1, projectId));//项目信息
				break;
			case 2://资产识别页面
				model.addAttribute("assetMap",assetService.findByprojectIdGroupByType(projectId));//资产信息
				break;
			case 3://重要资产赋值页面
				Map<String, List<Asset>> impAssetGroups = assetService.findImpProGroupByType(projectId);
				model.addAttribute("impAssetGroups", impAssetGroups); 
				break;
			case 4://威胁识别
				Map<String, List<MAsset>> threatGroups = threatService.showAllThreads(projectId);
				model.addAttribute("threatGroups", threatGroups); 
				break;
			case 5://脆弱性识别与赋值
				Map<String, List<MAsset>> weakGroups = weaknessService.showAllWeekness(projectId);
				model.addAttribute("weakGroups", weakGroups); 
				break;
			case 6:
				 Map<String, List<MResult>> resultMap = riskCalService.showResult(projectId);
				 model.addAttribute("resultMap", resultMap); 
				  break;
		}
		return model.toString();
	}
	
	/**
	 * 设置重要资产标准
	 * @param projectId
	 * @param groupIds
	 * @param currMenuId
	 * @param importance
	 * @return
	 */
	@PostMapping("/setImportance")
	public String setImportance( int projectId,	 String groupIds,  Integer currMenuId,Float importance){
		projectService.setImportance(projectId, importance);
		return "redirect:/pro/pageLink/" +projectId+"/"+groupIds+"/"+currMenuId ;
	}
	


	/**
	 * 获取左侧菜单接口
	 * @param groupArr 
	 * @return
	 */
	private  List<MMenu> getMuenList(Integer[]  groupArr){
		List<MMenu> menuList = new ArrayList<MMenu>();
		for (Integer groupId : groupArr) { //左侧菜单
			MMenu menu = leftMenuServiceImpl.findMenuByRoot(groupId);
			menuList.add(menu);
		}
		return menuList;
	}
	

	

	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	private String uploadGplot( MultipartFile file) {// 拓扑图上传
		
		if (null != file ) {
			String fileName = file.getOriginalFilename();// 获取文件名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));// 获取文件的后缀名
			fileName = UUID.randomUUID() + suffixName;
			try {
				Files.copy(file.getInputStream(), Paths.get(IMGPATH, fileName));// getOriginalFilename得到上传时的文件名
				return fileName;
			} catch (Exception e) {
				e.printStackTrace();
				return "-1";
			}
		}else{
			return "-1";
		}
		
	}
	
	
	/**
	 * 显示拓扑图
	 * @param filename
	 * @return
	 */
	@GetMapping("/{filename:.+}")
	@ResponseBody
	public ResponseEntity<?> getFile(@PathVariable String filename) { // 显示网络拓扑图
		try {
			return ResponseEntity.ok(resourceLoader.getResource("file:"
					+ Paths.get(IMGPATH, filename).toString()));
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

}
